package com.cskaoyan.shiro.config;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @ClassName ApplicationConfig
 * @Description: TODO
 * 之前的课程中，给大家介绍的是在springboot中去导入starter依赖，但是shiro例外，它的starter依赖写的不是特别好
 * 建议自己手动去注入
 * 在网络访问过程中，shiro根据用户访问的请求资源，去做对应的权限控制，需要配置一个shiroFilter来拦截所有的请求
 * 在此之前，我们需要配置一个securityManager
 * securityManager、shiroFilter、Realm、SessionManager
 * @Author 远志 zhangsong@cskaoyan.onaliyun.com
 * @Date 2023/5/19 14:15
 * @Version V1.0
 **/
@Configuration
public class ApplicationConfig {

    @Bean
    public SecurityManager securityManager(Realm realm, SessionManager sessionManager){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(realm);
        securityManager.setSessionManager(sessionManager);
        return securityManager;
    }

    @Bean
    public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
//        FilterChainDefinitionMap类型必须是linkedHashMap不可以是hashmap，必须要保障先后顺序
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
        //认证以及授权的地址配置在该处
        //链定义，设定各种不同的url和权限认证之间的关系，从上往下执行
        //anon：表示允许匿名访问；authc：表现需要认证才可以访问；logout：表示执行该条url，会销毁subject
        //roles：表示需要何种角色；perms：表示需要何种权限
//        filterChainDefinitionMap.put("/admin/auth/login", "anon");
//        filterChainDefinitionMap.put("/static/**", "anon");
//        filterChainDefinitionMap.put("/admin/admin/logout", "logout");
//        filterChainDefinitionMap.put("/admin/auth/info", "authc");
//        //凡是以/admin开头的除了上述介绍的url，全部都需要进行认证
//
//        //还需要相应的权限才可以
//        filterChainDefinitionMap.put("/admin/category/read","perms[admin:category:read]");
//
//
//        filterChainDefinitionMap.put("/admin/**", "authc");

        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return shiroFilterFactoryBean;
    }


    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager){
        AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
        advisor.setSecurityManager(securityManager);
        return advisor;
    }
}
